#define _CRT_SECURE_NO_WARNINGS 1

#include <vector>
using namespace std;

class Solution {
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int m;
    int n;
public:
    void dfs(vector<vector<int>>& heights, int i, int j, vector<vector<int>>& vis)
    {
        vis[i][j] = 1;
        for (int k = 0; k < 4; ++k)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && heights[i][j] <= heights[x][y] && vis[x][y] == 0)
            {
                dfs(heights, x, y, vis);
            }
        }
    }
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        m = heights.size();
        n = heights[0].size();
        vector<vector<int>> p(m, vector<int>(n));
        vector<vector<int>> a(m, vector<int>(n));
        vector<vector<int>> ret;
        for (int i = 0; i < m; ++i)
        {
            dfs(heights, i, 0, p);
            dfs(heights, i, n - 1, a);
        }
        for (int j = 0; j < n; ++j)
        {
            dfs(heights, 0, j, p);
            dfs(heights, m - 1, j, a);
        }
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                if (p[i][j] && a[i][j]) ret.push_back({ i,j });
        return ret;
    }
};